//
//  OAuth.swift
//  我的微博
//
//  Created by shmily on 15/7/29.
//  Copyright © 2015年 Stanford-IOS8-Swift-shmilyAshen. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuth: UIViewController ,UIWebViewDelegate{

     let client_id = "502828634"
     let redirect_uri = "http://www.baidu.com"
     let appSecret = "87009333d3a1b59b931d34b40633c232"
    
    ///静态 token
    private static var accessToken :String?
    
    override func loadView() {
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        title = "新浪微博授权"
        view = webView
        
        //默认进入界面
        webView.loadRequest(NSURLRequest(URL: NSURL(string: oauthUrl)!))
    }
    
    //MARK: - webView代理方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let str = request.URL!.absoluteString
        var code :String
        //授权不成功,返回到回调地址
        if !str.hasPrefix(redirect_uri)  {
            return true
        }
        
        if let query:NSString = request.URL?.query where query.hasPrefix("code=") {
            code = query.substringFromIndex(5)
            //获取 access_token
            loadAccessToken(code)
            close()
        } else {
            print("授权失败")
        }
        return false
    }
    
    ///获取loadAccess_token,若成功,继续获取用户信息(name,avator_large)
    func loadAccessToken (code :String) {
        NetworkingTools.sharedNetTool.loadAccess_token(code, finished: { (result, error) -> () in
            if error != nil || result == nil {
                self.errorDisplay()
            }
            //以上数据导入模型,并 get 剩下数据(name,avator_large)
            UserInfo(dict: result!).loadUserInfo({(error : NSError?) -> () in
                if error != nil {
                    self.errorDisplay()
                    print("\r\n加载用户信息(name,avator_large)时报错:")
                    print(error)
                    return
                }
                // 发送通知
                NSNotificationCenter.defaultCenter().postNotificationName(switchVCNotification, object: false)
                print("ok")
            })
        })
    }
    
    ///显示错误
    private func errorDisplay() {
        SVProgressHUD.showInfoWithStatus("网络不给力")
        //延时取消进度条
        let when = dispatch_time(DISPATCH_TIME_NOW,Int64(2 * NSEC_PER_SEC))
        dispatch_after(when, dispatch_get_main_queue(), { () -> Void in
            SVProgressHUD.dismiss()
        })
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    ///关闭控制器
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true,completion: nil)
    }
            
    //MARK: - 懒加载
    lazy var oauthUrl :String = {
        let str = "https://api.weibo.com/oauth2/authorize?client_id=\(self.client_id)&redirect_uri=\(self.redirect_uri)"
        return str
    }()
    
    //懒加载 webView
    lazy var webView :UIWebView = {
        let web = UIWebView()
        web.delegate = self
        return web
    }()
}
